package com.team.star.service.impl;


import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.team.star.dao.UserDAO;
import com.team.star.entity.pojo.User;
import com.team.star.entity.vo.UserVO;
import com.team.star.exception.ServiceExceptionHandler;
import com.team.star.service.UserService;
import com.team.star.utils.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    private final UserDAO userDAO;

    @Autowired
    public UserServiceImpl(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    /**
     * 用户登录
     * tips：关于登录、注册功能中用户密码的加密、解密，可以使用自定义注解完成
     */
//    @PasswordEncryptDecrypt(type = "decrypt") // 添加自定义注解，解密验证密码
    @Override
    public void login(UserVO userVO) {
        String username = userVO.getUsername();
        String password = userVO.getPassword();
        if (username == null) {
            throw new ServiceExceptionHandler(ResponseCode.USERNAME_IS_EMPTY);
        }
        User user = userDAO.selectOne(
                new QueryWrapper<User>()
                        .eq("username", username)
        );
        if (Objects.isNull(user)) {
            throw new ServiceExceptionHandler(ResponseCode.USER_NOT_EXIST);
        }
        //解密验证
        if (!BCrypt.checkpw(password, user.getPassword())) {
            throw new ServiceExceptionHandler(ResponseCode.PASSWORD_ERROR);
        }
    }

    /**
     * 用户注册
     */
    @Transactional
    @Override
//    @PasswordEncryptDecrypt(type = "encrypt") // 添加自定义注解，加密密码
    public void register(UserVO userVO) {
        String username = userVO.getUsername();
        String password = userVO.getPassword();
        if (username == null) {
            throw new ServiceExceptionHandler(ResponseCode.USERNAME_IS_EMPTY);
        }
        if (password == null) {
            throw new ServiceExceptionHandler(ResponseCode.PASSWORD_IS_EMPTY);
        }
        User user = userDAO.selectOne(
                new QueryWrapper<User>()
                        .eq("username", username)
        );
        if (user != null) {
            throw new ServiceExceptionHandler(ResponseCode.USER_EXIST);
        }
        //加密密码
        user = new User().setPassword(BCrypt.hashpw(password)).setUsername(username);
        userDAO.insert(user);
    }

    /**
     * 获取所有用户信息
     */
    @Override
    public List<User> getUserList() {
        return userDAO.selectList(null);
    }
}
